package com.swu.pad.comment.controller;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.formula.ptg.StringPtg;
import org.hibernate.boot.registry.selector.internal.StrategySelectorImpl;
import org.omg.Messaging.SyncScopeHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import org.w3c.dom.ls.LSInput;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.swu.pad.activity.dao.ActivityDao;
import com.swu.pad.assignment.dao.AssignmentDao;
import com.swu.pad.assignment.entity.Assignment;
import com.swu.pad.comment.dao.CommentQuestionDao;
import com.swu.pad.comment.dao.ConnectDatabase;
import com.swu.pad.course.dao.CourseDao;
import com.swu.pad.system.entity.User;
import com.swu.pad.util.MailUtil;
import com.swu.pad.util.EPLiteClient.EPLiteClient;
import com.swu.pad.util.MailUtil;

/**
 * 存储评论内容，因为插件原因不能使用SpringMVC，只能使用Servlet来存储
 * 
 * @author yuge
 *
 */
@Controller
public class SavaComment extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Autowired
	private ActivityDao activityDao;
	@Autowired
	private AssignmentDao assignmentDao;
	@Autowired
	private CourseDao courseDao;
	@Autowired
	private CommentQuestionDao commentQuestionDao;
	@Autowired
	private EPLiteClient epLiteClient;
	// @Autowired
	// private FbCommentService fbCommentService;
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 2 接收给属性赋值
		Connection conn = null;// 连接数据库
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String feedbackType = request.getParameter("radioValue");
		if (feedbackType == null) {
			feedbackType = "grade";
		}
		           //向被评论者发送邮件通知他有人评论他 start
		            String commenterIdMail=request.getParameter("Commenter");//这是插架评论 被评论的人
		            String authorIdMail=request.getParameter("AuthorID");// 被评论而且要给出评论分数的人
		            String commentIdMail= request.getParameter("commentId");// 评论在服务器上的id
		            String assId=request.getParameter("assignmentId");//作业id
		            String  courseName;//课程名字
		            String  assignmentName;//作业名称
		            assignmentName=assignmentDao.findOne(assId).getAssignmentName();
		            courseName=courseDao.findOne(assignmentDao.findOne(assId).getCourseId()).getCourseName();
//		            System.out.println("作者id="+authorIdMail);
//		            System.out.println("评论者id（给出评论的人）="+commenterIdMail);
//		            System.out.println("评论id="+commentIdMail);
					//1 先拿到被评论者信信息和评论者的信息
		            if(feedbackType.equals("0")){//添加评论
		            try {
						conn = ConnectDatabase.getConnection();
						String commenterName;
						String authorName;
						String email;
						String findCommentersql="select *from user where id=?";//被评论者信息
						String findAuthorsql="select *from user where id=?";//评论者信息
					
						//查询
						pstmt = (PreparedStatement) conn.prepareStatement(findCommentersql);//查询被评论者
						pstmt.setString(1,commenterIdMail);
						rs = pstmt.executeQuery();
						
					
						if (rs.next()) {
							 email=rs.getString(2);//被评论者 邮箱地址
						     commenterName=rs.getString(4);//被评论者真实姓名
						     pstmt = (PreparedStatement) conn.prepareStatement(findAuthorsql);//查询评论者
							 pstmt.setString(1,authorIdMail);
							 rs = pstmt.executeQuery();
							 rs.next();
							 authorName=rs.getString(4);
							 //发送邮件
							 try{
						            //MailUtil.sendMail(email,commenterName,courseName,assignmentName);
						        	//System.out.println("提醒作者有人评论邮件发送成功！");
						        } catch (Exception e) {
								   //System.out.println("邮件发送失败！管理员请及时处理！");
								}			
								
						     
						}else{
							String name=epLiteClient.getAuthorName(commenterIdMail);
							//System.out.println("(添加评论)查询发送邮件功能，被评论者姓名，根据id没有查询到结果!id="+commenterIdMail+"--name="+name);
							
						    
						}
						
						
						
					} catch (Exception e) {
						//System.out.println("插件评论 发送邮件出现异常！");
					}
		            }//否则则为 反馈  或者打分类型
		            else {
		            	
		            	if(feedbackType.equals("grade")){
		            	 try {
								conn = ConnectDatabase.getConnection();
								String commenterName = null;
								String authorName;
								String email;
								String findCommentersql="select *from user where id=?";//被评论者信息
								String findAuthorsql="select *from user where id=?";//评论者信息
							    String findcommentAuthorId="select * from fbcomment where comment_id=? and feedback_type=?";
								//查询
								pstmt = (PreparedStatement) conn.prepareStatement(findCommentersql);//查询被评论者
								pstmt.setString(1,commenterIdMail);
								rs = pstmt.executeQuery();
						        if (rs.next()) {
								     commenterName=rs.getString(4);//被评论者真实姓名
								}else{
									String name=epLiteClient.getAuthorName(commenterIdMail);
									//System.out.println("插件评(grade)论查询发送邮件功能，被评论者姓名，根据id没有查询到结果!id="+commenterIdMail+"--name="+name);
								}
								
						      //查询
								pstmt = (PreparedStatement) conn.prepareStatement(findcommentAuthorId);//查询评论者
								pstmt.setString(1,commentIdMail);
								pstmt.setString(2,"0");
								rs = pstmt.executeQuery();
						        if (rs.next()) {
								   authorIdMail=rs.getString(4);//找到评价者的id
								   //查询
									pstmt = (PreparedStatement) conn.prepareStatement(findAuthorsql);//查询评论者
									pstmt.setString(1,authorIdMail);
									rs = pstmt.executeQuery();
									if(rs.next()){
									email=rs.getString(2);
									authorName=rs.getString(4);
								   //发送邮件
									 try{
								            //MailUtil.sendMailToGrade(email,authorName,courseName,assignmentName);
								        	//System.out.println("向评论者发送有给评论打分邮件发送成功！");
								        } catch (Exception e) {
										   //System.out.println("邮件发送失败！管理员请及时处理！");
										}			
									}
								}else{
									String name=epLiteClient.getAuthorName(authorIdMail);
									//System.out.println("插件评(grade)论查询发送邮件功能，添加评论者姓名，根据id没有查询到结果!id="+authorIdMail+"--name="+name);
								}
								
								
							} catch (Exception e) {
								//System.out.println("插件评论 发送邮件出现异常！");
							}
		            	}
					}
		
		
		
		

	

		if ((feedbackType != null) && feedbackType.equals("0") || feedbackType.equals("Reply")) {
			String assignmentId = request.getParameter("assignmentId");
			String commentId = request.getParameter("commentId");// 评论在服务器上的id
			String type = request.getParameter("type");// 评论属于哪一类

			int feedbackScore = Integer.parseInt(request.getParameter("replayStar").toString());
			String timestamp = request.getParameter("timestamp");// 时间戳
			String authorId = request.getParameter("AuthorID");// 被评论而且要给出评论分数的人
			String activityId = request.getParameter("activityId");
			String commenterId = request.getParameter("Commenter");
			String padId = request.getParameter("padId");
			padId = padId == null ? "" : new String(padId.getBytes("ISO-8859-1"), "UTF-8");
			String commentText = request.getParameter("text");
			
			//2018年4月23日晚 发现服务器加上这段有乱码，但在本地加上这段 没有乱码commentText = commentText == null ? "" : new String(commentText.getBytes("ISO-8859-1"), "UTF-8");
			System.out.println("commentText="+commentText);
			
			
			// 向数据库插入数据
  
			try {
				// 插入comments语句
				String sql = "insert into fbcomment (comment_id,type,feedback_type,feedback_score,timestamp,commenter_id,author_id,comment_text,pad_id,assignment_id,activity_id) values(?,?,?,?,?,?,?,?,?,?,?)";
				// 获得与数据库的连接
				conn = ConnectDatabase.getConnection();
				pstmt = (PreparedStatement) conn.prepareStatement(sql);
				pstmt.setString(1, commentId);
				pstmt.setString(2, type);
				pstmt.setString(3, feedbackType);
				pstmt.setInt(4, feedbackScore);
				pstmt.setString(5, timestamp);
				pstmt.setString(6, commenterId);// 内容
				pstmt.setString(7, authorId);
			    pstmt.setString(8, commentText);
				pstmt.setString(9, padId);
				pstmt.setString(10, assignmentId);
				pstmt.setString(11, activityId);
				pstmt.executeUpdate();// 执行语句update
				//System.out.println("插入成功");
				// 插入成功
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("向数据库插入fbcomments发生异常！");
			}
		} else {// 说明是grade
			String fbid = "";
			String assignmentId = request.getParameter("assignmentId");// 1
			String commentId = request.getParameter("commentId");// 评论在服务器上的id 1
			String type = "null_type";// 评论属于哪一类
			int feedbackScore = -1;
			String timestamp = request.getParameter("timestamp");// 时间戳 1
			String authorId = request.getParameter("AuthorID");// 被评论而且要给出评论分数的s人
																// 1
			String activityId = request.getParameter("activityId");// 1
			String commenterId = request.getParameter("Commenter"); // 1
			String padId = request.getParameter("padId");// 1
			padId = padId == null ? "" : new String(padId.getBytes("ISO-8859-1"), "UTF-8");// 1
			String commentText = request.getParameter("text");
			//2018年4月23日晚 发现服务器加上这段有乱码，但在本地加上这段 没有乱码commentText = commentText == null ? "" : new String(commentText.getBytes("ISO-8859-1"), "UTF-8");
			try {
				// 插入comments语句
				String sql = "insert into fbcomment (comment_id,type,feedback_type,feedback_score,timestamp,commenter_id,author_id,comment_text,pad_id,assignment_id,activity_id) values(?,?,?,?,?,?,?,?,?,?,?)";
				// 获得与数据库的连接
				conn = ConnectDatabase.getConnection();
				pstmt = (PreparedStatement) conn.prepareStatement(sql);
				pstmt.setString(1, commentId);
				pstmt.setString(2, type);
				pstmt.setString(3, feedbackType);
				pstmt.setInt(4, feedbackScore);
				pstmt.setString(5, timestamp);
				pstmt.setString(6, commenterId);
				pstmt.setString(7, authorId);
				pstmt.setString(8, commentText);
				pstmt.setString(9, padId);
				pstmt.setString(10, assignmentId);
				pstmt.setString(11, activityId);
				pstmt.executeUpdate();// 执行语句update
				// 插入成功

				String findFbidSql = "select *from fbcomment where comment_id=? and feedback_type=? and timestamp=? and commenter_id=? and author_id=? and assignment_id=? and activity_id=?";
				pstmt = (PreparedStatement) conn.prepareStatement(findFbidSql);
				pstmt.setString(1, commentId);
				pstmt.setString(2, feedbackType);
				pstmt.setString(3, timestamp);
				pstmt.setString(4, commenterId);
				pstmt.setString(5, authorId);
				pstmt.setString(6, assignmentId);
				pstmt.setString(7, activityId);
				rs = pstmt.executeQuery();
				if (rs.next()) {
					fbid = rs.getString(1);
				}
				// 拿到外键遍历数据
				String multipleString = request.getParameter("multipleList");
				String singleString = request.getParameter("singleList");
				String[] sub = multipleString.split("\\.");
				String[] sub2 = singleString.split("\\.");
				for (int i = 0; i < sub.length; i++) {
					String qid = "";
					String question = "";
					String score = "";
					String qtype = "multiple";
					String[] ss = sub[i].split("\\,");
					for (int j = 0; j < ss.length; j++) {
						String[] sss = ss[j].split("\\:");
						for (int k = 0; k < sss.length; k++) {
							if (sss[k].equals("radio")) {
								qid = sss[k + 1];
							} else if (sss[k].equals("score")) {
								score = sss[k + 1];
							} else {

							}
						}
					}
					// 存数据

					if (qid != null && !(qid.equals("")) && !(qid.equals("undefined"))) {
						question = commentQuestionDao.findOne(qid).getQuestion();
						String isql = "insert into fbgrade (fb_id,feedback,score,type,template_id) values(?,?,?,?,?)";
						// 获得与数据库的连接
						pstmt = (PreparedStatement) conn.prepareStatement(isql);
						pstmt.setString(1, fbid);
						pstmt.setString(2, question);
						pstmt.setString(3, score);
						pstmt.setString(4, qtype);
						pstmt.setString(5, qid);

						pstmt.executeUpdate();// 执行语句update
					}
				}

				for (int i = 0; i < sub2.length; i++) {
					String qid = "";
					String question = "";
					String score = "";
					String qtype = "single";
					String[] ss = sub2[i].split("\\,");
					for (int j = 0; j < ss.length; j++) {
						String[] sss = ss[j].split("\\:");
						for (int k = 0; k < sss.length; k++) {
							if (sss[k].equals("radio")) {
								qid = sss[k + 1];
							} else if (sss[k].equals("score")) {
								score = sss[k + 1];
							} else {

							}
						}
					}
					// 存数据
					if (qid != null && !(qid.equals("")) && !(qid.equals("undefined"))) {
						question = commentQuestionDao.findOne(qid).getQuestion();
						String isql = "insert into fbgrade (fb_id,feedback,score,type,template_id) values(?,?,?,?,?)";
						// 获得与数据库的连接
						pstmt = (PreparedStatement) conn.prepareStatement(isql);
						pstmt.setString(1, fbid);
						pstmt.setString(2, question);
						pstmt.setString(3, score);
						pstmt.setString(4, qtype);
						pstmt.setString(5, qid);
						pstmt.executeUpdate();// 执行语句update
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("向数据库插入fbcomments发生异常！");
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
